package com.nic.view.widget;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Environment;

import com.nic.view.ViewConfig;

import java.io.File;
import java.io.IOException;

public class AudioRecorder {

    private int BASE = 1;

    public static final String RECORD_PATH = ViewConfig.SDCARD_PATH + "/voiceRecord/";
    private static int SAMPLE_RATE_IN_HZ = 22050;

    private MediaRecorder mMediaRecorder;

    private AudioManager audioMgr = null; // Audio管理器，用了控制音量
    private int maxVolume = 80; // 最大音量值
    private int curVolume = 40; // 当前音量值
    private int stepVolume = 0; // 每次调整的音量幅度
    private int maxDuration = 60 * 1000;

    public int getMaxDuration() {
        return maxDuration;
    }

    public void setMaxDuration(int maxDuration) {
        this.maxDuration = maxDuration;
    }

    /**
     * 初始化播放器、音量数据等相关工作
     */
    private void initPlayWork() {
        audioMgr = (AudioManager) ViewConfig.applicationContext.getSystemService(Context.AUDIO_SERVICE);
        // 获取最大音乐音量
        maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 初始化音量大概为最大音量的1/2
        curVolume = maxVolume / 2;
        // 每次调整的音量大概为最大音量的1/6
        stepVolume = maxVolume / 6;

        // 从麦克风源进行录音
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        // 设置输出格式
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        // 设置编码格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        // recorder.setAudioChannels(AudioFormat.CHANNEL_CONFIGURATION_MONO);
        mMediaRecorder.setAudioSamplingRate(SAMPLE_RATE_IN_HZ);
        mMediaRecorder.setAudioEncodingBitRate(SAMPLE_RATE_IN_HZ);
    }

    /**
     * 调整音量
     */
    private void adjustVolume() {
        audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume,
                AudioManager.FLAG_PLAY_SOUND);
    }

    //按下增大音量
    public void press() {
        curVolume += stepVolume;
        if (curVolume >= maxVolume) {
            curVolume = maxVolume;
        }
        adjustVolume();
    }

    public AudioRecorder() {
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        }
        initPlayWork();
    }


    public String sanitizePath(String path) {
        // 设置保存文件路径
        String smPath = RECORD_PATH + path + ".m4a";//
        return smPath;
    }

    public void start(String mPath) throws IOException {
        try {
            String state = Environment.getExternalStorageState();
            if (!state.equals(Environment.MEDIA_MOUNTED)) {
                throw new IOException("SD Card is not mounted,It is  " + state
                        + ".");
            }
            File directory = new File(mPath).getParentFile();
            if (!directory.exists() && !directory.mkdirs()) {
                throw new IOException("Path to file could not be created");
            }
            mMediaRecorder.setMaxDuration(getMaxDuration());
            mMediaRecorder.setOutputFile(mPath);
            //录音开始
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            press();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 录音结束
    public void stop() throws IOException {
        mMediaRecorder.stop();
        mMediaRecorder.release();
        mMediaRecorder = null;
    }

    public double getAmplitude() {
        if (mMediaRecorder != null) {
            return (mMediaRecorder.getMaxAmplitude());
        } else
            return 0;
    }

    public double getDecibel() {
        double db = 0;// 分贝
        if (mMediaRecorder != null) {
            double ratio = (double) mMediaRecorder.getMaxAmplitude() / BASE;
            if (ratio > 1) {
                db = 20 * Math.log10(ratio);
            }
        }
        return db;
    }
}
